package me.zhengjie.config;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.boot.autoconfigure.orm.jpa.HibernateProperties;
import org.springframework.boot.autoconfigure.orm.jpa.HibernateSettings;
import org.springframework.boot.autoconfigure.orm.jpa.JpaProperties;
import org.springframework.boot.orm.jpa.EntityManagerFactoryBuilder;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Primary;
import org.springframework.data.jpa.repository.config.EnableJpaRepositories;
import org.springframework.orm.jpa.JpaTransactionManager;
import org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean;
import org.springframework.transaction.PlatformTransactionManager;
import org.springframework.transaction.annotation.EnableTransactionManagement;

import javax.persistence.EntityManager;
import javax.sql.DataSource;
import java.util.Map;

/**
 * @Description: 主数据源配置
 * @date
 */
@Configuration
@EnableTransactionManagement
@EnableJpaRepositories(entityManagerFactoryRef = "entityManagerFactoryEladmin",
        transactionManagerRef = "transactionManagerEladmin",
        basePackages = {"me.zhengjie.*.repository", "me.zhengjie.repository", "me.zhengjie.modules.*.repository"})
public class EladminDataSourceConfig {

    @Autowired
    @Qualifier("eladminDataSource")
    private DataSource eladminDataSource;

    @Autowired
    private HibernateProperties hibernateProperties;

    @Autowired
    private JpaProperties jpaProperties;

    @Primary
    @Bean(name = "entityManagerEladmin")
    public EntityManager entityManager(EntityManagerFactoryBuilder builder) {
        return entityManagerFactoryEladmin(builder).getObject().createEntityManager();
    }

    @Primary
    @Bean(name = "entityManagerFactoryEladmin")    //实体工厂
    public LocalContainerEntityManagerFactoryBean entityManagerFactoryEladmin(EntityManagerFactoryBuilder builder) {
        return builder.dataSource(eladminDataSource)
                .properties(getHibernateProperties())
                .packages("me.zhengjie.domain", "me.zhengjie.modules.*.domain")     //实体类所在位置
                .persistenceUnit("eladminPersistenceUnit")
                .build();
    }

    @Primary
    @Bean(name = "transactionManagerEladmin")
    public PlatformTransactionManager transactionManager(EntityManagerFactoryBuilder builder) {
        return new JpaTransactionManager(entityManagerFactoryEladmin(builder).getObject());
    }

    private Map<String, Object> getHibernateProperties() {
        return hibernateProperties.determineHibernateProperties(jpaProperties.getProperties(), new HibernateSettings());
    }

}